package com.it.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替换httpServlet 根据方法的最后一段路径进行方法的分发
 */
public class baseServlet extends HttpServlet {

    //根据方法最后一段路径进行方法的分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取路径
        String URI = req.getRequestURI(); // Brand_case/brand/

        //2.获取最后一段路径 实现方法分发

            //获取最后一个斜杠位置
        int index = URI.lastIndexOf("/");

            //从最后一个斜杠开始截取 名称是对应方法名称
            // 从index 开始截取是/selectAll 需要index+1获取对应方法名称
        String substring = URI.substring(index+1);

        //执行对应的方法
            //1.获取this对应的字节码
            //this是谁？  this 谁调用我（this 所在的方法），我（this）代表谁
            //System.out.println(this);
        Class<? extends baseServlet> aCl = this.getClass();


        try {
            Method method = aCl.getMethod(substring, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}
